#include <iostream>
#include <cstdio>
#include <cassert>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>


using namespace std;

int main()
{
    int pipefd[2]={0};//// pipefd[0(嘴巴，读书)]: 读端 , pipefd[1(钢笔，写)]: 写端
    int n = pipe(pipefd);
    assert(n != -1); // debug assert, release assert
    (void)n;
    #ifdef DEBUG
        cout << "pipefd[0]: " << pipefd[0] << endl; // 3
        cout << "pipefd[1]: " << pipefd[1] << endl; // 4
    #endif

    pid_t id=fork();
    if(id==0)
    {
        close(pipefd[1]);
        char buff[1024*8];
        while(true)
        {
            //close(pipefd[0]);
            ssize_t s = read(pipefd[0], buff, sizeof(buff) - 1);
            if(s>0)
            {
                buff[s] = 0;
                cout << "child get a message[" << getpid() << "] Father# " << buff << endl;
            }
            else
            {
                cout << "writer quit(father), me quit!!!" << endl;
                break;
            }
            //make
            //sleep(10);
        }
        close(pipefd[0]);//关闭文件，可以不用
        exit(0);
        //return 0;
    }

    else if(id>0)
    {
        close(pipefd[0]);
        string message = "我是父进程，我正在给你发消息\n";
        int count = 0;
        char send_buffer[1024 * 8];

        while(true)
        {
            //构建一个变化的字符串
            snprintf(send_buffer, sizeof(send_buffer), "%s[%d] : %d",
                 message.c_str(), getpid(), count++);//写到一个字符串
           write(pipefd[1], send_buffer, strlen(send_buffer));
            sleep(10);
           /*if(count==5)
           {
                cout<<count<<endl;
                break;
           }*/
        }

        close(pipefd[1]);
        //进程等待
        //int status;
        pid_t ret = waitpid(id,NULL,0);
        cout << "id : " << id << " ret: " << ret <<endl;
        assert(ret > 0); 
        (void)ret;

    }
    return 0;
}